<template>
  <div class="suyuanPage">
    <div class="suyuanPicture">
      <div class="pictureBox">
        <img :src="suyuanDetail.icon" alt="" />
        <van-uploader :after-read="afterRead">
          <div class="changeImg">更换图片</div>
        </van-uploader>
      </div>
    </div>
    <div class="suyuan">
      <div class="suyuanName">
        <div class="tit">产品名称</div>
        <div class="content">
          <van-field v-model="suyuanDetail.typeName" disabled placeholder="请输入产品名称" />
        </div>
      </div>
      <div class="suyuanInfo">
        <div class="tit">产品介绍</div>
        <div class="content info">
          <van-field
            v-model="suyuanDetail.customText"
            type="textarea"
            :autosize="{ minHeight: 110, maxHeight: 110 }"
            placeholder="请输入产品介绍"
          />
        </div>
      </div>
    </div>
    <div class="report">
      <van-cell title="检测报告" is-link @click="goReportEdit()"  />
    </div>
    <div class="submit" @click="submit()">编辑</div>
  </div>
</template>

<script>
import { fileImgApi, getDetailByIdApi, editSuyuanDetailApi } from '@/api/tracing'
import { Toast } from 'vant'
export default {
  name: 'ShuzhongtianH5Edit',

  data () {
    return {
      filePath: '',
      fileList: [],
      suyuanDetail: {
        seedType: '',
        icon: '',
        customText: ''
      },
      tsId: '',
      baseId: '',
      userId: ''
    }
  },

  mounted () {
    this.tsId = this.$route.query.tsId
    this.baseId = this.$route.query.baseId
    this.userId = this.$route.query.userId
    console.log(this.userId)
    if (Object.keys(this.$store.state.editData).length !== 0) {
      this.suyuanDetail = this.$store.state.editData
    } else {
      this.getDetail()
    }
  },

  methods: {
    async getDetail () {
      const res = await getDetailByIdApi(this.tsId)
      console.log(res)
      this.suyuanDetail = res.data
      this.$store.commit('setValue', this.suyuanDetail)
    },
    goReportEdit () {
      this.$store.commit('setEditData', this.suyuanDetail)
      this.$router.push({
        path: `/report?tsId=${this.tsId}&baseId=${this.baseId}&userId=${this.userId}`
      })
    },
    /**
 * 提交编辑的溯源详情
 * 该函数通过调用API接口editSuyuanDetailApi来提交编辑后的溯源详情数据
 * 如果服务器返回的code为200，则表示编辑成功，会依次清除编辑数据和报告，
 * 显示编辑成功的提示信息，并重新获取详情数据最后跳转到产品记录页面
 */
    async submit () {
      // 调用API提交编辑后的溯源详情数据
      const res = await editSuyuanDetailApi(this.suyuanDetail)
      console.log(res)
      // 判断服务器返回的结果码，若为200则表示编辑成功
      if (res.code === 200) {
        // 清除编辑数据和报告
        this.$store.commit('removeEditData')
        this.$store.commit('removeReport')
        // 显示编辑成功的提示信息
        Toast.success('编辑成功')
        // 重新获取详情数据
        this.getDetail()

        // 设置定时器，半秒后跳转到产品记录页面
        setTimeout(() => {
          this.$router.push({
            path: `/productRecord?tsId=${this.tsId}&baseId=${this.baseId}&userId=${this.userId}&tabval=1`
          })
        }, 500)
      }
    },
    // 上传文件
    afterRead (file) {
      // 此时可以自行将文件上传至服务器
      const that = this
      console.log(file)
      const img = new Image() // 创建对象，这个img就是传给上面的compress
      img.src = file.content
      const reader = new FileReader()
      reader.readAsDataURL(file.file)
      img.onload = async function () { // 回调
        const idCard = that.compress(img)// 这个id_card就是压缩后的一串base64代码，目测3M图片压缩后800kb
        // 这下面写接口，这里传base64格式给后台
        const formData = new FormData()
        // 转化成png格式
        const nameImg = new Date().getTime() + '.png'
        formData.append('file', that.dataURLtoBlob(idCard), nameImg)
        const res = await fileImgApi(formData)
        console.log(res)
        that.suyuanDetail.icon = res.data
        console.log(that.suyuanDetail)
      }
    },
    // 压缩图片
    compress (img) {
      let url = ''
      var w = Math.min(700, img.width)// 当图片像素>700的时候，等比例压缩，这个数字可以调
      var h = img.height * (w / img.width)
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      canvas.width = w
      canvas.height = h
      ctx.drawImage(img, 0, 0, w, h)
      url = canvas.toDataURL('image/png', 1)// 1代表精细度，越高越好
      return url
    },
    // base64转Blob
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    }
  }
}
</script>

<style lang="scss" scoped>
.suyuanPage {
  width: 375px;
  height: 812px;
  background: #f6f8fc;
  border-radius: 0px 0px 0px 0px;
  padding: 16px;
  .suyuanPicture {
    width: 343px;
    height: 154px;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    padding: 21px;
    .pictureBox {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;

      img {
        width: 88px;
        height: 88px;
        background: #d9d9d9;
        border-radius: 50%;
      }
      .changeImg {
        color: #19b560;
      }
    }
  }
  .suyuan {
    width: 343px;
    height: 249px;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    padding: 10px;
    margin: 8px 0;
    .suyuanName {
      margin-bottom: 10px;
    }
    .tit {
      margin-bottom: 10px;
    }
    .content {
      height: 38px;
      display: flex;
      ::v-deep .van-cell {
        padding: 3px 3px;
        background: transparent;
        font-size: 16px;
        line-height: 1.1;
      }
      border-bottom: 1px solid #e7e9e8;
    }
    .info {
      width: 319px;
      height: 118px;
      background: #e7e9e8;
      border-radius: 4px 4px 4px 4px;
      border-bottom: none !important;
      padding: 2px;
    }
  }
  .report {
    border-radius: 8px 8px 8px 8px;
    overflow: hidden;
  }
}
.submit {
  width: 343px;
  height: 44px;
  background: #19b560;
  border-radius: 8px 8px 8px 8px;
  text-align: center;
  line-height: 44px;
  color: #fff;
  position: absolute;
  bottom: 44px;
}
</style>
